package com.bbh.data.ui.service;

import com.bbh.data.service.api.UserVo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class UserHystrixService {

    @Autowired
    RestTemplate restTemplate; //1

    @HystrixCommand(fallbackMethod = "fallbackSome") //2
    public List<UserVo> save() {
        String url = "http://data-service-provider/user/save";
        HttpEntity<Object> request = new HttpEntity<Object>(createHeaders("user", "3d17c02d-8abe-44e6-8550-02709bc8fb28"));
        ResponseEntity<List> response = restTemplate.exchange(url, HttpMethod.GET, request, List.class, new HashMap<String, Object>());
        return response.getBody();
    }

    private HttpHeaders createHeaders(String username, String password) {
        return new HttpHeaders() {
            {
                String auth = username + ":" + password;
                byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
                String authHeader = "Basic " + new String(encodedAuth);
                set("Authorization", authHeader);
            }
        };
    }


    public List<UserVo> fallbackSome() {
        List<UserVo> list=new ArrayList<>();
        UserVo userVo=new UserVo();
        userVo.setUsername("保存错误");
        list.add(userVo);
        return list;
    }
}